package com.nbcio.modules.erp.coupon.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nbcio.modules.erp.base.entity.ErpCustomer;
import com.nbcio.modules.erp.base.service.IErpCustomerService;
import com.nbcio.modules.erp.cart.entity.SysUser;
import com.nbcio.modules.erp.cart.service.ISysUserServiceNew;
import com.nbcio.modules.erp.coupon.entity.CouponCustomer;
import com.nbcio.modules.erp.coupon.entity.MallCoupon;
import com.nbcio.modules.erp.coupon.entity.UserCouponRelations;
import com.nbcio.modules.erp.coupon.mapper.CouponCustomerMapper;
import com.nbcio.modules.erp.coupon.service.ICouponCustomerService;
import com.nbcio.modules.erp.coupon.service.IMallCouponService;
import com.nbcio.modules.erp.coupon.service.UserCouponRelationsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 优惠券发放
 * @Author: nbacheng
 * @Date:   2024-04-22
 * @Version: V1.0
 */
@Service
public class CouponCustomerServiceImpl extends ServiceImpl<CouponCustomerMapper, CouponCustomer> implements ICouponCustomerService {


    @Autowired
    private IErpCustomerService customerService;

    @Autowired
    private ISysUserServiceNew sysUserService;

    @Autowired
    private UserCouponRelationsService userCouponRelationsService;

    @Autowired
    private IMallCouponService mallCouponService;

    /**
     * 发放优惠券之后生成用户和优惠券关联表
     * @param couponCustomer
     */
    @Override
    @Transactional
    public void addUserCoupon(CouponCustomer couponCustomer) {

        //根据客户id查找手机号
        LambdaQueryWrapper<ErpCustomer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ErpCustomer::getId, couponCustomer.getCustomerId());
        List<ErpCustomer> erpCustomerList = customerService.list(queryWrapper);
        if (CollectionUtil.isEmpty(erpCustomerList)){
            throw new RuntimeException("未找到对应的客户");
        }

        //根据手机号查找用户id
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        List<String> phoneList = erpCustomerList.stream().map(ErpCustomer::getPhone).collect(Collectors.toList());
        wrapper.in(SysUser::getPhone,phoneList);
        List<SysUser> sysUserList = sysUserService.list(wrapper);

        if (CollectionUtil.isEmpty(sysUserList)){
            throw new RuntimeException("根据客户未找到对应的用户");
        }

        List<String> userIdList = sysUserList.stream().map(SysUser::getId).collect(Collectors.toList());
        String couponId = couponCustomer.getCouponId();

        //查询优惠券，比较发放数量是否小于剩余数量，以及小于单客户优惠数量
        LambdaQueryWrapper<MallCoupon> couponWrapper = new LambdaQueryWrapper<>();
        couponWrapper.eq(MallCoupon::getId,couponId);
        MallCoupon mallCoupon = mallCouponService.getOne(couponWrapper);

        if (mallCoupon.getRemainingQuantity().compareTo(couponCustomer.getIssueNum()) < 0){
            throw new RuntimeException("优惠券数量不足,剩余优惠券数量还有"+mallCoupon.getRemainingQuantity()+"张");
        }

        if (mallCoupon.getMaxPerUser().compareTo(couponCustomer.getIssueNum()) < 0){
            throw new RuntimeException("超过单用户领取优惠券次数，该优惠券单用户只能领取"+mallCoupon.getMaxPerUser()+"张");
        }

        userIdList.forEach(userId ->{
            saveUserCouponRelation(userId, couponId, new Date(),couponCustomer.getIssueNum());
//            updateMallCoupon(couponId,couponCustomer.getIssueNum());
        });
    }


    /**
     * 保存单个用户优惠券关联关系。
     *
     * @param userId         用户ID
     * @param couponId       优惠券ID
     * @param issueAt       发放时间
     * @param num            发放数量
     */
    private void saveUserCouponRelation(String userId, String couponId, Date issueAt,BigDecimal num) {

        LambdaQueryWrapper<UserCouponRelations> query = new LambdaQueryWrapper<>();
        query.eq(UserCouponRelations::getUserId, userId)
                .eq(UserCouponRelations::getCouponId, couponId);
        if (userCouponRelationsService.count(query) > 0) {
            // 如果已经存在，则更新数量
            UserCouponRelations relations = userCouponRelationsService.getOne(query);
            relations.setIssueNum(relations.getIssueNum().add(num));
            userCouponRelationsService.updateById(relations);
        }else {
            UserCouponRelations userCouponRelations = new UserCouponRelations();
            userCouponRelations.setCouponId(couponId);
            userCouponRelations.setUserId(userId);
            userCouponRelations.setId(RandomUtil.randomString(32));
            userCouponRelations.setIssueNum(num);
            userCouponRelations.setIssueAt(issueAt);
            userCouponRelationsService.save(userCouponRelations);
        }
    }


    /**
     * 更新优惠券数量
     * @param coupon_id
     */
    private void updateMallCoupon(String coupon_id,BigDecimal num){
        //领取了优惠券，那么对应的优惠券数量要改变
        //查出对应的优惠券
        MallCoupon mallCoupon = mallCouponService.getById(coupon_id);
        mallCoupon.setRemainingQuantity(mallCoupon.getRemainingQuantity().subtract(num));
        mallCoupon.setUsedQuantity(mallCoupon.getUsedQuantity().add(num));
        mallCouponService.updateById(mallCoupon);
    }
}
